﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;

namespace BSPortal.Usercontrol
{
    public partial class Cart : System.Web.UI.UserControl
    {
        private float fee;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadCity();
                LoadDistrict();
                LoadWard();

                LoadData();
                LoadUserInfo();
            }
            CheckCart();
        }

        protected void LoadCity()
        {
            var mainService = Common.GetClientService();
            var listCity = mainService.GetAllCity().OrderBy(row => row.Name);

            ddlCity.DataValueField = "CityId";
            ddlCity.DataTextField = "Name";
            ddlCity.DataSource = listCity;
            ddlCity.DataBind();
        }

        protected void LoadDistrict()
        {
            if (ddlCity.SelectedValue != string.Empty)
            {
                var mainService = Common.GetClientService();
                var listDistrict = mainService.GetAllDistrict(int.Parse(ddlCity.SelectedValue)).OrderBy(row => row.Name);

                ddlDistrict.DataValueField = "DistrictId";
                ddlDistrict.DataTextField = "Name";
                ddlDistrict.DataSource = listDistrict;
                ddlDistrict.DataBind();
            }
        }

        protected void LoadWard()
        {
            if (ddlDistrict.SelectedValue != string.Empty)
            {
                var mainService = Common.GetClientService();
                var listWard =
                    mainService.GetAllWard(int.Parse(ddlCity.SelectedValue), int.Parse(ddlDistrict.SelectedValue)).OrderBy(row => row.Name);

                ddlWard.DataValueField = "WardId";
                ddlWard.DataTextField = "Name";
                ddlWard.DataSource = listWard;
                ddlWard.DataBind();
            }
        }

        protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadDistrict();
            ddlDistrict_SelectedIndexChanged(sender, e);
        }

        protected void ddlDistrict_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadWard();
        }

        protected void CheckCart()
        {
            if (System.Web.HttpContext.Current.Session["Cart"] == null)
            {
                divContent.Visible = false;
                cartGrid.Visible = false;
                lblAlert.Visible = true;
            }
            else
            {
                var cart = (Dictionary<int, int>)System.Web.HttpContext.Current.Session["Cart"];
                if (cart.Count == 0)
                {
                    divContent.Visible = false;
                    cartGrid.Visible = false;
                    lblAlert.Visible = true;
                }
                else
                {
                    divContent.Visible = true;
                    cartGrid.Visible = true;
                    lblAlert.Visible = false;
                }
            }
        }

        protected void LoadUserInfo()
        {
            MainService mainService = Common.GetClientService();
            if (System.Web.HttpContext.Current.Session["Username"] != null)
            {
                var user = mainService.GetUserById(Session["Username"].ToString());
                if (user == null)
                    return;
                txtName.Text = user.Name;
                txtEmail.Text = user.Email;
                txtPhone.Text = user.Phone;
                txtAddress.Text = user.Address;
                ddlCity.SelectedValue = user.City.ToString();
                ddlDistrict.SelectedValue = user.District.ToString();
                ddlWard.SelectedValue = user.Ward.ToString();
            }
            else
            {
                ddlCity.SelectedValue = Common.GetValueInAppSetting("HCMCity_Id", "1");
            }
        }

        protected void LoadData()
        {
            var mainService = new MainService();

            if (System.Web.HttpContext.Current.Session["Cart"] != null)
            {
                var cart = (Dictionary<int, int>)System.Web.HttpContext.Current.Session["Cart"];
                var listProduct = new List<Product>();
                double total = 0;
                foreach (var id in cart.Keys)
                {
                    var product = mainService.GetProductById((short)id);
                    product.Amount = cart[id];
                    listProduct.Add(product);
                    total += product.Amount * ((int)product.Price * (1 - (double)product.Discount));
                }

                cartGrid.DataSource = listProduct;
                var datakeys = new string[1];
                datakeys[0] = "ProductId";
                cartGrid.DataKeyNames = datakeys;
                cartGrid.DataBind();

                if (listProduct.Count > 0)
                {
                    fee = Common.GetFee(listProduct);
                    var temp = Math.Round((double)fee / 10, 0) * 10;
                    lblFee.Text = temp.ToString("#,###");
                    if (fee == 0)
                        lblFee.Text = "0";
                }

                if (total > 0)
                {
                    total = Math.Round(total / 10, 0) * 10;
                    lblTotal.Visible = true;
                    lblTotalPrice.InnerText = total.ToString("#,###");
                }
                else
                {
                    lblTotal.Visible = false;
                }
            }
        }

        protected void cartGrid_RowEditing(object sender, GridViewEditEventArgs e)
        {
            cartGrid.EditIndex = e.NewEditIndex;
            LoadData();
        }

        protected void cartGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var cart = (Dictionary<int, int>)Session["Cart"];
            cart.Remove(int.Parse(cartGrid.DataKeys[e.RowIndex].Value.ToString()));
            System.Web.HttpContext.Current.Session["Cart"] = cart;
            if (cart.Count == 0)
                Response.Redirect("");
            LoadData();
        }

        protected void cartGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var cart = (Dictionary<int, int>)System.Web.HttpContext.Current.Session["Cart"];
            foreach (var control in cartGrid.Rows[e.RowIndex].Cells[4].Controls)
            {
                if (control.GetType() == typeof(TextBox))
                {
                    TextBox textBox = (TextBox)control;
                    cart[int.Parse(cartGrid.DataKeys[e.RowIndex].Value.ToString())] = int.Parse(textBox.Text);
                    break;
                }

            }
            System.Web.HttpContext.Current.Session["Cart"] = cart;
            cartGrid.EditIndex = -1;
            LoadData();
        }

        protected void cartGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            cartGrid.EditIndex = -1;
            LoadData();
        }

        protected void btnCheckout_Click(object sender, EventArgs e)
        {
            if (Session["Cart"] == null)
                return;

            var cart = (Dictionary<int, int>)Session["Cart"];

            if (cart.Count <= 0)
                return;

            MainService mainService = Common.GetClientService();
            var listProduct = new List<Product>();
            foreach (var id in cart.Keys)
            {
                var product = mainService.GetProductById((short)id);
                product.Amount = cart[id];
                listProduct.Add(product);
            }
            if (listProduct.Count > 0)
            {
                fee = Common.GetFee(listProduct);
            }

            int orderId = mainService.CreateOrder(txtName.Text, txtAddress.Text, txtEmail.Text, txtNote.Text,
                                                  txtPhone.Text, homeCheck.Checked ? "1" : "2",
                                                  fee, int.Parse(ddlStatus.SelectedValue), int.Parse(ddlCity.SelectedValue), int.Parse(ddlDistrict.SelectedValue), int.Parse(ddlWard.SelectedValue));
            if (orderId != 0)
            {
                foreach (var key in cart.Keys)
                {
                    mainService.CreateOrderDetail((short)orderId, (short)cart[key], (short)key);
                }

            }

            Response.Write("<script>alert(\'Bạn đã đặt hàng thành công. Mã đặt hàng là: dh00" + orderId + "\');</script>");
            Response.Write("<script>window.location.href = '/gio-hang.html';</script>");

            System.Web.HttpContext.Current.Session["Cart"] = null;
        }
    }
}